package sample;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.List;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;

import cn.DESedeTool;
import cn.Header;
import cn.SAGClientConfig;
import cn.eshore.bnet.sag.fax.Attachment;
import cn.eshore.bnet.sag.fax.ClientUtils;
import cn.eshore.bnet.sag.fax.DeliveryState;
import cn.eshore.bnet.sag.fax.Fax;
import cn.eshore.bnet.sag.fax.FaxMessage;
import cn.eshore.bnet.sag.fax.FaxService;
import cn.eshore.bnet.sag.fax.GetAttachments;
import cn.eshore.bnet.sag.fax.GetAttachmentsResponse;
import cn.eshore.bnet.sag.fax.GetStateResponse;
import cn.eshore.bnet.sag.fax.MessageType;
import cn.eshore.bnet.sag.fax.PolicyException_Exception;
import cn.eshore.bnet.sag.fax.QueryResponse;
import cn.eshore.bnet.sag.fax.ReceiveResponse;
import cn.eshore.bnet.sag.fax.SendResponse;
import cn.eshore.bnet.sag.fax.ServiceException_Exception;


public class FaxDemo {
	private Fax port;

	public void init(String wsdlurl) throws MalformedURLException {
		URL wsdlURL = new URL(wsdlurl);
		FaxService ss = new FaxService(wsdlURL);
		port = ss.getFaxServicePort();
	}
	public static void main(String[] args) throws Exception {
		try {
			System.out.println("参数配置（通过开发指南中的“自测申请”获取测试所需参数）......");
			SAGClientConfig.fax_wsdl = "http://125.88.125.218/sag-server-fax/fax?wsdl";// 传真服务地址
			SAGClientConfig.si = "92";// SI帐号 92；1001
			SAGClientConfig.password = "abcd1234";// 密码 abcd1234；slc66win
			SAGClientConfig.fax_accessNumber = "02080720172";// 龙骞接入号

			System.out.println("构建SOAP消息头Header（参数描述参考《广东商企平台能力开放接口协议-总册v0.1》）......");
			Header header = null;
			// 此处为测试配置，正式上线时，需要根据当前使用者设置消息头中的user product bnetId productSpec
			header = ClientUtils.createHeader(SAGClientConfig.si,
					SAGClientConfig.password, null, null, null, null,
					SAGClientConfig.fax_accessNumber, null);

			FaxDemo demo = new FaxDemo();
			demo.init(SAGClientConfig.fax_wsdl);

			// 测试发送传真。参考文档《广东商企平台能力开放接口协议-传真能力分册》9.1章节
			demo.send(header);
//			demo.send2(header);

			// 测试查询传真状态。参考文档《广东商企平台能力开放接口协议-传真能力分册》9.2章节
//			demo.getState(header, "47431");

			// 测试获取传真接口。
//			String receiver = "02080720157";
//			demo.receive(header,receiver);

			// 测试获取附件接口。
//			String messageId = "19357";
//			header.setCustomerNumber("02080720172");
//			demo.getAttachments(header,messageId);

			// 测试查询收发记录接口。
//			header.setCustomerNumber("02085616227");
//			demo.query(header);
			
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (PolicyException_Exception e) {
			System.out.println("ErrorCode : " + e.getErrorCode());
			System.out.println("ErrorMessage : " + e.getErrorMessage());
		} catch (ServiceException_Exception e) {
			System.out.println("ErrorCode : " + e.getErrorCode());
			System.out.println("ErrorMessage : " + e.getErrorMessage());
		} 
	}
	
	/**
	 * 发送传真（适合模式1、3、5，参考《广东商企平台能力开放接口协议-总册》）
	 * @param header
	 */
	public String send(Header header) 
		throws PolicyException_Exception,ServiceException_Exception {
		System.out.println("构建SOAP消息体Body(参数描述参考《广东商企平台能力开放接口协议-传真能力分册》)......");
		cn.eshore.bnet.sag.fax.Send parameters = new cn.eshore.bnet.sag.fax.Send();
		String sender = "02085616227"; // 07592460296发送者号码，由领航平台在开通SI产品时，作为产品开通信息传递给SI应用系统。对于大客户的业务模式，发送号码由
		String receiver = "02038095600"; //02038095600 五楼：02038095302电话号码格式，请参见《广东商企平台能力开放接口协议-传真分册.doc》

		parameters.setSender(sender);
		parameters.setCorrelator(System.currentTimeMillis() + "");//SI生成并记录，ISAG-B回调通知发送结果时包含该信息
		parameters.setSubject("主题ymy060901");
		parameters.getReceivers().add(receiver); // 接收方最多12个
		
		Attachment attachment = new Attachment();//添加传真附件
		File file = new File("c:\\1303970799471_fax1.txt"); // 改为本地文件！！1303970799471_fax1.txt；test.tif
		attachment.setName(file.getName());
		attachment.setData(new DataHandler(new FileDataSource(file)));
		parameters.getFiles().add(attachment);
//		parameters.setNotifyUrl("http://125.88.125.218/sag-server-fax/siFaxNotification");//可选，如需要发送结果通知则改为SI自己的回调地址

		System.out.println("调用发送传真接口......");
		SendResponse response = port.send(parameters, header);
		System.out.println("requestId为" + response.getRequestId()+ "（可用于查询传真发送状态）");
		return response.getRequestId();
	}
	
	/**
	 * 发送传真（适合模式2、4，参考《广东商企平台能力开放接口协议-总册》）
	 * @param header
	 */
	public String send2(Header header) 
		throws PolicyException_Exception,ServiceException_Exception {
		System.out.println("构建SOAP消息体Body(参数描述参考《广东商企平台能力开放接口协议-传真能力分册》)......");
//		String customerNumber = "07503266125"; // 客户号码，请参见《广东商企平台能力开放接口协议-传真分册.doc》
		String customerNumber = ""; // 客户号码，请参见《广东商企平台能力开放接口协议-传真分册.doc》07503861100
	    String customerNumberPwd = ""; // 客户号码的密码；大客户模式，无需密码
		header.setCustomerNumber(customerNumber);
		// (timestamp+客户号码的密码)与(SI的密码的前8位)进行3DES加密 
		String signature = DESedeTool.encrypt(header.getTimestamp()
				+ customerNumberPwd, SAGClientConfig.password.substring(0, 8));
		header.setCustomerNumberSignature(signature);
		
		cn.eshore.bnet.sag.fax.Send parameters = new cn.eshore.bnet.sag.fax.Send();
		String sender = ""; // 发送者号码，由领航平台在开通SI产品时，作为产品开通信息传递给SI应用系统。对于大客户的业务模式，发送号码由
		//测试号：02037864003；02037864009;软终端号：02087189475
		String receiver = "02038095600"; //02080720172 02038095600  五楼：02038095302 十二楼：02038095201 电话号码格式，请参见《广东商企平台能力开放接口协议-传真分册.doc》
//		String receiver = "02080710010"; //02080720172 02038095600  五楼：02038095302 十二楼：02038095201 华为软终端：02080718622 电话号码格式，请参见《广东商企平台能力开放接口协议-传真分册.doc》
		parameters.setSender(sender);
		parameters.setCorrelator(System.currentTimeMillis() + "");//SI生成并记录，ISAG-B回调通知发送结果时包含该信息
		parameters.setSubject("主题0118");
		parameters.getReceivers().add(receiver); // 接收方最多12个
//		parameters.getReceivers().add("02080710010"); // 接收方最多12个
		
		Attachment attachment = new Attachment();//添加传真附件
		File file = new File("c:\\test.tif"); // 改为本地文件！！
		attachment.setName(file.getName());
		attachment.setData(new DataHandler(new FileDataSource(file)));
		parameters.getFiles().add(attachment);
		//状态通知回调地址
//		parameters.setNotifyUrl("http://125.88.125.218/sag-server-fax/siFaxNotification");// 需要改为SI自己的回调地址

		System.out.println("调用发送传真接口......");
		SendResponse response = port.send(parameters, header);
		System.out.println("requestId为" + response.getRequestId()
				+ "（可用于查询传真发送状态）");
		return response.getRequestId();
	}
	
	/**
	 * 获取传真发送状态
	 * @param header
	 * @param requestId
	 */
	public void getState(Header header,String requestId) 
		throws PolicyException_Exception,ServiceException_Exception {
		System.out.println("构建SOAP消息体Body(参数描述参考《广东商企平台能力开放接口协议-传真能力分册》)......");
		cn.eshore.bnet.sag.fax.GetState parameters = new cn.eshore.bnet.sag.fax.GetState();
		parameters.setRequestId(requestId);

		System.out.println("调用获取传真发送状态接口......");
		GetStateResponse response = port.getState(parameters, header);
		if (response != null && response.getDeliveryState() != null
				&& response.getDeliveryState().size() > 0) {
			List<DeliveryState> stateList = response.getDeliveryState();
			for (DeliveryState state : stateList) {
				System.out.println("接收号为 " + state.getReceiver()
						+ " 的传真的发送状态为 " + state.getState() + "（状态码参考传真能力分册）");
			}
		} else {
			System.out.println("没有与requestId=" + requestId + "匹配的记录");
		}

	}
	
	
	/**
	 * 获取传真
	 * @param header
	 * @param requestId
	 */
	public void receive(Header header,String receiver) 
	throws PolicyException_Exception,ServiceException_Exception {
		System.out.println("构建SOAP消息体Body(参数描述参考《广东商企平台能力开放接口协议-传真能力分册》)......");
		cn.eshore.bnet.sag.fax.Receive parameters = new cn.eshore.bnet.sag.fax.Receive();
		parameters.setReceiver(receiver);// 接收者

		System.out.println("调用获取传真接口......");
		ReceiveResponse response = port.receive(parameters, header);
		if (response != null && response.getMessages() != null
				&& response.getMessages().size() > 0) {
			List<FaxMessage> messageList = response.getMessages();
			for (FaxMessage message : messageList) {
				System.out.println("messageId:" + message.getMessageId()
						+ " sender:" + message.getSender() + " receiver:"
						+ message.getReceiver() + " subject:"
						+ message.getSubject() + " timeStamp:"
						+ message.getTimeStamp() + " timeStamp:"
						+ message.getTimeStamp());
			}
		} else {
			System.out.println("没有与receiver=" + receiver + "匹配的记录");
		}

	}

	/**
	 * 获取附件
	 * @param header
	 * @param requestId
	 */
	public void getAttachments(Header header, String messageId)
			throws PolicyException_Exception, ServiceException_Exception {
		System.out.println("构建SOAP消息体Body(参数描述参考《广东商企平台能力开放接口协议-传真能力分册》)......");
		cn.eshore.bnet.sag.fax.GetAttachments parameters = new cn.eshore.bnet.sag.fax.GetAttachments();
		parameters.setMessageId(messageId);// 接收者

		System.out.println("调用获取附件接口......");
		GetAttachmentsResponse response = port.getAttachments(parameters,
				header);
		if (response != null && response.getFiles() != null
				&& response.getFiles().size() > 0) {
			List<Attachment> attachmentList = response.getFiles();
			try {
				for (Attachment attachment : attachmentList) {
					System.out.println("name:" + attachment.getName());
					String file = ClientUtils.saveAttachment(attachment,
							"e:/attachments");
					System.out.println("file:" + file);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("没有与messageId=" + messageId + "匹配的记录");
		}
	}
	

	/**
	 * 查询收发记录
	 * 
	 * @param header
	 */
	public void query(Header header)
		throws PolicyException_Exception, ServiceException_Exception {
		System.out.println("构建SOAP消息体Body(参数描述参考《广东商企平台能力开放接口协议-传真能力分册》)......");
		cn.eshore.bnet.sag.fax.Query parameters = new cn.eshore.bnet.sag.fax.Query();
		parameters.setCustomerNumber("02085616227");
//		parameters.setCustomerNumber(header.getCustomerNumber());
		parameters.setMessageType(MessageType.SEND);
		parameters.setStartRow(0);
		parameters.setEndRow(10);
		// XMLGregorianCalendar startTime = new XMLGregorianCalendar();
		// parameters.setStartTime(new XMLGregorianCalendar().);
		// parameters.setEndTime(value);
		// parameters.setSender("");
		// parameters.setReceiver("");

	
		System.out.println("调用获取附件接口......");
		QueryResponse response = port.query(parameters, header);

		System.out.println("-------Query Result---------");
		System.out.println("TotalSize:"
				+ response.getQueryResult().getTotalSize());
		for (Object message : response.getQueryResult().getMessages()) {
			FaxMessage fax = (FaxMessage) message;

			// 获取附件
			GetAttachments getAttachments = new GetAttachments();
			getAttachments.setMessageId(fax.getMessageId());
			System.out.println("messageId:" + fax.getMessageId());

			GetAttachmentsResponse getAttachmentsResponse;
			getAttachmentsResponse = port
					.getAttachments(getAttachments, header);
			String file = "";
			if (getAttachmentsResponse.getFiles().size() > 0) {
				try {
					file = ClientUtils.saveAttachment(getAttachmentsResponse
							.getFiles().get(0), "e:/attachments");// 改为本地路径
				} catch (IOException e) {
					e.printStackTrace();
				} 
			}
			System.out.println("messageId:" + fax.getMessageId() + ",sender:"
					+ fax.getSender() + ",receiver:" + fax.getReceiver()
					+ ",file" + file);
			List<DeliveryState> deliveryStates = fax.getDeliveryStates();
			for (DeliveryState deliveryState : deliveryStates) {
				System.out.println("deliveryState:"
						+ deliveryState.getReceiver() + " "
						+ deliveryState.getState());
			}
		}
	}
}
